package com.boot.apollo.modules.thread;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;


import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.List;
import java.util.Map;

/**
 * DeferredResult 包装器
 *
 *
 * @author Jason Song(song_s@ctrip.com)
 */
public class DeferredResultWrapper {
  private static final long TIMEOUT = 60 * 1000;//60 seconds
  /**
   * 未修改时的 ResponseEntity 响应，使用 302 状态码。
   */
  private static final ResponseEntity<List<String>>
      NOT_MODIFIED_RESPONSE_LIST = new ResponseEntity<>(HttpStatus.NOT_MODIFIED);


  /**
   * 响应的 DeferredResult 对象
   */
  private DeferredResult<ResponseEntity<List<String>>> result;


  /**
   * 构造函数，使用默认的超时时间，和状态
   */
  public DeferredResultWrapper() {
    result = new DeferredResult<>(TIMEOUT, NOT_MODIFIED_RESPONSE_LIST);
  }

   // 客户端超时回调
  public void onTimeout(Runnable timeoutCallback) {
    result.onTimeout(timeoutCallback);
  }

  // 服务端超时回调
  public void onCompletion(Runnable completionCallback) {
    result.onCompletion(completionCallback);
  }

  // 设置通知
  public void setResult(String notification) {
    setResult(Lists.newArrayList(notification));
  }

  /**
   *  设置通知的消息，和返回的状态
   */
  public void setResult(List<String> notifications) {

    result.setResult(new ResponseEntity<>(notifications, HttpStatus.OK));
  }

  public DeferredResult<ResponseEntity<List<String>>> getResult() {
    return result;
  }
}
